package mytool;

import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class HashValue {
	public static final String MD5 = "MD5";

	public static final String SHA1 = "SHA1";

	public static final String SHA256 = "SHA-256";

	public static final String SHA384 = "SHA-384";

	public static final String SHA512 = "SHA-512";

	public static String getHash(File file, String hashType)
			throws NoSuchAlgorithmException, Exception {
		FileInputStream in = new FileInputStream(file);
		byte[] buf = new byte[1024];

		MessageDigest md5 = MessageDigest.getInstance(hashType);
		int numRead;
		while ((numRead = in.read(buf)) != -1) {
			md5.update(buf, 0, numRead);
		}
		in.close();
		byte[] bs = md5.digest();
		StringBuilder sb = new StringBuilder(bs.length * 2);
		for (byte b : bs) {
			sb.append(Integer.toHexString(b & 0xff));// Integer.toHexString(b&0xff)方法中，b被转为int，负数前补24个1，b&0xff去掉byte的负数符号位
		}
		String s = sb.toString();
		return s;
	}

	public static String getMD5(String s,String charset) throws UnsupportedEncodingException,
			NoSuchAlgorithmException {
		byte[] b = s.getBytes(charset);
		MessageDigest md5 = MessageDigest.getInstance("md5");
		byte[] bs = md5.digest(b);
		StringBuilder sb = new StringBuilder(bs.length * 2);
		for (byte bb : bs) {
			sb.append(Integer.toHexString(bb & 0xff));// Integer.toHexString(b&0xff)方法中，b被转为int，负数前补24个1，b&0xff去掉byte的负数符号位
		}
		String ss = sb.toString();
		System.out.println(ss);
		return ss;
	}

	public static void main(String[] args) throws NoSuchAlgorithmException,
			Exception {
		// String s = getHash(new
		// File("/home/tarena/Desktop/Struts2.pdf"),SHA512);
		// System.out.println(s);
		String s =getMD5("opensesame","gbk");//贺安泰，"gbk"fa401d293abd19d7a98149e741f5d4e
		
	}

}
